package vetxsoft.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import vetxsoft.bean.ClienteBean;
import vetxsoft.entity.Cliente;
import vetxsoft.system.IVetexsoftSystem;

/**
 * @author user
 */
@FacesConverter(forClass = Cliente.class, value = "ClienteConvertor")
public class ClienteConvertor implements Converter {

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        if (value == null || value.trim().equalsIgnoreCase("Seleccione...") || value.trim().length() == 0) {
            return null;
        }
        try {
            IVetexsoftSystem sanmarinoSystem = ((ClienteBean) fc.getApplication().getELResolver().getValue(fc.getELContext(), null, "clienteBean")).getVetexsoftSystem();
            Cliente cliente = sanmarinoSystem.buscarCliente(value);
            return cliente;
        } catch (Exception _exc) {
            return null;
        }
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Cliente) {
            Cliente cliente = (Cliente) value;
            return cliente.getCedula() + "";
        } else {
            throw new IllegalArgumentException("object " + value + " is of type " + value.getClass().getName() + "; expected type: " + Cliente.class.getName());
        }
    }
}